//
//  SaveSettingViewController.m
//  Riese
//
//  Created by air on 2019/11/2.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "SaveSettingViewController.h"
#import "ConnectCell.h"
#import "DeviceCommand.h"
#import <MMAlertView.h>

@interface SaveSettingViewController () <UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate, DeviceCommandDelegate> {
    DeviceCommand *device;

    CBCentralManager *manager;
    CBPeripheral *peripheralFind;
    
    Boolean bReSend;
    NSInteger isSuccess;
    NSTimer *timer;
}

@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, strong) NSArray *deviceArr;

@property (nonatomic, strong) FMDatabase *db;
@property (nonatomic, strong) NSArray *dataArr;

@end

@implementation SaveSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColor(243, 243, 243);
    self.navigationItem.title = NSLocalizedString(@"Device", nil);
    
    isSuccess = 0;
    
    #if TARGET_IPHONE_SIMULATOR
        
    #else
        device = [[DeviceCommand alloc] init];
    #endif
    
    [self makeNav];
    [self connectDevice];
    [self makeUI];
}

- (void)makeNav {
    UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshBtn.frame = CGRectMake(0, 0, kNavHeight, kNavHeight);
    [refreshBtn setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
    [refreshBtn addTarget:self action:@selector(refreshBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshBtn];
}

- (void)makeUI {
    self.mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kBottomSafeHeight)];
    self.mainTable.backgroundColor = [UIColor whiteColor];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.showsVerticalScrollIndicator = NO;
    self.mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.mainTable];
}

#pragma mark - tableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"ConnectCell";
    ConnectCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
    }
    
    if (self.deviceArr.count > 0) {
        cell.titleStr = self.deviceArr[indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.deviceArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if ((manager != nil) && (peripheralFind != nil)) {
//        [manager connectPeripheral:peripheralFind options:nil];
//    }
//
    if ((manager != nil) && (peripheralFind != nil)) {
        [SVProgressHUD showWithStatus:NSLocalizedString(@"Connection", nil)];
        [manager connectPeripheral:peripheralFind options:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self->isSuccess == 0) {
                [SVProgressHUD dismiss];
                [YJProgressHUD showMessage:NSLocalizedString(@"Setup failed", nil) inView:self.view];
            }
        });
    }
}

#pragma mark - 连接设备
- (void)connectDevice {
    
//    device = [[DeviceCommand alloc] init];
    device.delegate = self;

    bReSend = YES;
    
    NSLog(@"findDevice");
    
    if (manager != nil)
    {
        if (peripheralFind != nil)
        {
            [manager cancelPeripheralConnection:peripheralFind];
        }
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        
        [manager scanForPeripheralsWithServices:nil options:dic];
    }
    else
    {
        CBCentralManager *managerFind = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        
        manager = managerFind;
    }
    
    // 30秒之后没有搜到设备提示
    [SVProgressHUD showWithStatus:NSLocalizedString(@"searching", nil)];
    timer = [NSTimer timerWithTimeInterval:30.0 target:self selector:@selector(timerRun) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerRun {
    [SVProgressHUD dismiss];
    [YJProgressHUD showMessage:NSLocalizedString(@"Device not found", nil) inView:self.view];
}

#pragma mark ----<DeviceCommandDelegate>
-(void)receivePM10Param:(NSDictionary *)dicParam//15.1.20
{
    NSLog(@"getPM10Param %@", dicParam);
}

-(void)getOperateResult:(NSDictionary *)dicDeleteResult
{
    isSuccess = 1;
    // 设置参数成功调用此方法
    if ([dicDeleteResult[@"OperateResult"] containsString:@"SetParamSucceed"]) {
        if ([self.isClear isEqualToString:@"1"]) {
            // 清除设备数据
            [device peripheral:peripheralFind deleteData:0];
        }
        
        [SVProgressHUD dismiss];
        [YJProgressHUD showMessage:NSLocalizedString(@"Set up successfully", nil) inView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }
    else if ([dicDeleteResult[@"OperateResult"] containsString:@"DeleteSucceed"]) {
        
    }
    else {
        [SVProgressHUD dismiss];
        [YJProgressHUD showMessage:NSLocalizedString(@"Setup failed", nil) inView:self.view];
    }
    NSLog(@"getOperateResult %@", dicDeleteResult);
}

#pragma mark ----  <CBCentralManagerDelegate>
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSMutableString *nsmstring = [NSMutableString stringWithString:@"UpdateState:"];
    switch (central.state)
    {
        case CBManagerStateUnknown:
        {
            [nsmstring appendString:@"Unknown\n"];
            break;
        }
        case CBManagerStateUnsupported:
        {
            [nsmstring appendString:@"Unsupported\n"];
            break;
        }
        case CBManagerStateUnauthorized:
        {
            [nsmstring appendString:@"Unauthorized\n"];
            break;
        }
        case CBManagerStateResetting:
        {
            [nsmstring appendString:@"Resetting\n"];
            break;
        }
        case CBManagerStatePoweredOff:
        {
            [nsmstring appendString:@"PoweredOff\n"];
            if(peripheralFind != NULL)
            {
                [manager cancelPeripheralConnection:peripheralFind];
            }
            break;
        }
        case CBManagerStatePoweredOn:
        {
            [nsmstring appendString:@"PoweredOn\n"];
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
            
            [manager scanForPeripheralsWithServices:nil options:dic];

            break;
        }
            
        default:
        {
            [nsmstring appendString:@"none\n"];
            break;
        }
    }
    
    NSLog(@"%@", nsmstring);
}

//发现设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSString *identifier = [NSString stringWithFormat:@"%@", peripheral.identifier];
    NSString * str = kStringIsEmpty(peripheral.name);
    if ([str length] > 0 && [str containsString:@"PM"]) {
        self.deviceArr = @[kStringIsEmpty(peripheral.name)];
        [SVProgressHUD dismiss];
        [timer invalidate];
//        [self.deviceArr addObject:kStringIsEmpty(peripheral.name)];
        
        [manager stopScan];
        peripheralFind = peripheral;
        [self.mainTable reloadData];
    }
    else if (identifier.length > 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        
        [manager scanForPeripheralsWithServices:nil options:dic];
    }
    else {
        self.deviceArr = @[];
    }
    
    NSLog(@"discover %@",peripheral.name);
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"connect %@",peripheral.name);
//    [self.view makeToast:@"连接成功"];
    
    // 设置参数
//    [device getPM10Param:peripheral];
    [device peripheral:peripheralFind language:[self.languageStr integerValue] saveTime:[self.lengthStr integerValue] heartSound:[self.soundStr integerValue] ShieldAnalysis:0];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
//    [self.view makeToast:@"连接失败"];
    NSLog(@"fail to connect %@",peripheral.name);
    NSLog(@"%@", error);
}

#pragma mark - button Click
- (void)refreshBtnClick {
    [self connectDevice];
}

@end
